//
//  剑指 05. 替换空格.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/10.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class SolutionSord05 {
    // 先计算数组的空间
    // 精妙之处是从后向前移动
    func replaceSpace(_ s: String) -> String {
        // 假设有空间3倍于字符串长度的数组
        var charsArray: [Character] = Array(repeating: Character(" "), count: s.count * 3)
        var charsArrayIndex:Int = charsArray.count - 1
        for item in Array(s).reversed() {
            if item == " " {
                charsArray[charsArrayIndex] = "0"
                charsArrayIndex -= 1
                charsArray[charsArrayIndex] = "2"
                charsArrayIndex -= 1
                charsArray[charsArrayIndex] = "%"
                charsArrayIndex -= 1
            } else {
                charsArray[charsArrayIndex] = item
                charsArrayIndex -= 1
            }
        }
        var str = ""
        for index in charsArrayIndex + 1..<charsArray.count {
            let cStr = String(charsArray[index])
            str.append(cStr)
        }
        return str
    }
    static func test() {
        let solution = SolutionSord05()
        let nums = "We are happy."
        let result = solution.replaceSpace(nums)
        print(result)
    }
}
